package org.midi.j2me.component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;

public class SoundPlayer {
	public String phoneType;

	public final String[] mediaType = { "audio/x-wav", "audio/midi",
			"audio/mpeg", "audio/amr" };

	public SoundPlayer(String phoneType) {
		this.phoneType = phoneType;
	}

	public InputStream getInputStream(byte[] data) {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		return (InputStream) bais;
	}

	public Player createPlayer(InputStream is, String mediaType, int loop) {
		Player player = null;
		if (is != null) {
			if (mediaType.equals("wav")) {
				try {
					player = Manager.createPlayer(is, this.mediaType[0]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			if (mediaType.equals("mid")) {
				try {
					player = Manager.createPlayer(is, this.mediaType[1]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (mediaType.equals("mpeg")) {
				try {
					player = Manager.createPlayer(is, this.mediaType[2]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (mediaType.equals("amr")) {
				try {
					player = Manager.createPlayer(is, this.mediaType[3]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (player != null) {
				player.setLoopCount(loop);
			}

			return player;

		}
		return null;
	}

	public Player createPlayer(String fileName, int loop) {
		InputStream is = getClass().getResourceAsStream(fileName);
		String suffix = fileName.substring(fileName.indexOf('.') + 1, fileName
				.length());
		return createPlayer(is,suffix,loop);
	}
	
	public void playSound(Player player){
		try{
			if(player.getState()!=400){
				player.start();
			}
		}catch(Exception e){			
		}
	}
	
	public void pauseSound(Player player){
		try{
			if(player.getState()==400){
				player.stop();
			}
		}catch(Exception e){
			
		}
	}
	
	public void stopSound(Player player){
		try{
			if(player.getState()==400){
				player.stop();
			}
			if(!phoneType.equals("NOKIA")){
				player.deallocate();
			}
		}catch(Exception e){
			
		}			
	}
	
	public void closeSound(Player player){
		try{
			this.stopSound(player);
			player.close();
		}catch(Exception e){			
		}
	}
}
